<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 200px;
            height: 200px;
            margin: 100px auto;
        }
    </style>
</head>

<body>
    <div>
        <div style="background-color: red;" id="test"></div>
        <button id="p">防抖</button><br />
        <button id="jie">防抖</button><br />

    </div>
    <script>
        const vcolor = ['red', 'blue', 'green', 'yellow', 'orange', 'pink', 'purple']
        // 防抖
        var p = document.getElementById('p')
        p.addEventListener("click", fangdou(pu))
        // 防抖函数
        function fangdou(fn) {
            let timeout = null
            return function () {
                clearTimeout(timeout)
                timeout = setTimeout(() => {
                    fn.apply(this, arguments)
                }, 1000)
            }

        }
        // 用户点击函数
        function pu() {
            console.log(1)
            var index = Math.floor(Math.random() * vcolor.length)
            test.style.backgroundColor = vcolor[index];
        }

        // 节流
        var jie = document.getElementById("jie")
        jie.addEventListener("click", jieliu(liu))
        var test = document.getElementById("test")
        // 节流函数
        function jieliu(fn) {
            let can = true
            return function () {
                if (!can) return
                can = false
                setTimeout(() => {
                    fn.apply(this, arguments);
                    can = true
                }, 1000);
            }
        }
        function liu() {
            console.log("我使节流")
            var index = Math.floor(Math.random() * vcolor.length)
            test.style.backgroundColor = vcolor[index];
        }

    </script>

</body>

</html>